package com.yingyi.es;

import com.yingyi.utils.ESClientUtil;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;

public class ESTest {
    /**
     * @Description: 批量添加数据
     * @Author: Director
     * @Date: 2022/7/23 0:02
     * @return: void
     **/
    @Test
    public void testBatch() throws Exception {
        // 1.获取ES连接
        TransportClient client = ESClientUtil.getClient();
        // 2.创建批量操作对象
        BulkRequestBuilder bulk = client.prepareBulk();
        // 3.批量创建文档，放入批量操作对象中
        for (int i = 2; i < 100; i++) {
            IndexRequestBuilder builder = client.prepareIndex("pethome", "user", i + "").setSource(
                    XContentFactory.jsonBuilder()
                            .startObject()
                            .field("id", i - 1)
                            .field("name", "我在源码学习Java!" + i)
                            .field("age", i - 1)
                            .field("sex", i%2)
                            .endObject()
            );
            BulkResponse result = bulk.add(builder).get();
            System.out.println(result.status());
        }
        // 4.关闭连接
        client.close();
    }

    /**
     * 复杂查询
     *
     * - 查询用户表
     * - name包含：我在源码
     * - age在1~12之间
     * - sex=1
     * - 每页大小2
     * - 从2页开始查
     * - 按照age倒序
     *
     *  查询条件顺序：
     *      query 开启条件查询，会进行相似度计算
     *          bool 多条件查询
     *              must 必须匹配 and
     *                  match/term 分词/不分词匹配查询
     *              filter DSL过滤，不会计算匹配度，结果会缓存
     *                  term 不分词条件查询
     *      from
     *      size
     *      sort
     * @throws Exception
     */
    @Test
    public void complexSearch() throws Exception{
        // 获取连接
        TransportClient client = ESClientUtil.getClient();

        // 创建查询的对象
        SearchRequestBuilder searchRequestBuilder = client.prepareSearch("pethome");

        // 按条件查询
        // query bool
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //must
        boolQuery.must(QueryBuilders.matchQuery("name", "我在源码"));

        //filter
        boolQuery.filter(QueryBuilders.termQuery("sex", 1))
                .filter(QueryBuilders.rangeQuery("age").gte(10).lte(30));

        //添加查询条件
        searchRequestBuilder.setQuery(boolQuery);
        searchRequestBuilder.setFrom(0);
        searchRequestBuilder.setSize(10);
        searchRequestBuilder.addSort("age", SortOrder.DESC);

        SearchHits hits = searchRequestBuilder.get().getHits();
        for (SearchHit hit : hits.getHits()) {
            System.out.println(hit.getSourceAsMap());
        }
    }
}
